package org.shean.app.rssreader;

import org.shean.app.rssreader.services.RSSRefreshService;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;

public class SettingActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener{
	
	private ListPreference mRefreshTime;
	private ListPreference mFontSize;
	public static final String PREFS_NAME = "RSSPrefsFile";
	
	@Override
    public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
        addPreferencesFromResource(R.xml.setting);

        PreferenceScreen prefSet = getPreferenceScreen();
        
        mRefreshTime = (ListPreference) prefSet.findPreference("auto_refresh");
        
        mRefreshTime.setOnPreferenceChangeListener(this);
        
        mFontSize = (ListPreference) prefSet.findPreference("font_setting");
        mFontSize.setOnPreferenceChangeListener(this);
	}
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if(preference == mRefreshTime)
		{
			int value = Integer.parseInt(newValue.toString());
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("auto_refresh_time", value);
			editor.commit();
			
			mRefreshTime.setValue(Integer.toString(value));
			PendingIntent mAlarmSender = PendingIntent.getService(SettingActivity.this,
	                0, new Intent(SettingActivity.this, RSSRefreshService.class), 0);
			
			AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.cancel(mAlarmSender);
            
            if(value > 0)
            {
            	long firstTime = SystemClock.elapsedRealtime() + value * 60* 1000;
            	am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        firstTime, value * 60* 1000, mAlarmSender);
            }
		}
		else if(preference == mFontSize)
		{
			int value = Integer.parseInt(newValue.toString());
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("font_size", value);
			editor.commit();
		}
		return true;
	}
	
	@Override
    public void onResume() {
        super.onResume();
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        int index = settings.getInt("auto_refresh_time", 0);
        mRefreshTime.setValue(Integer.toString(index));
        
        index = settings.getInt("font_size", 0);
        mFontSize.setValue(Integer.toString(index));
	}

}
